package com.zhouyang.imtest.websocket;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhouyang.imtest.dao.MessageDao;
import com.zhouyang.imtest.entity.Message;
import com.zhouyang.imtest.entity.UserData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author:ZhouYang
 * @Description: 统一处理器
 * @Date: Created in 2020/7/16 14:22
 * @Modified By：  处理消息的Handler
 */

@Component
public class MessageHandler extends TextWebSocketHandler {


    @Autowired
    private MessageDao messageDao;

    private static final ObjectMapper MAPPER = new ObjectMapper();
    /**
     * 储存所有和WebSocket建立连接的用户Id信息
     */
    private static final Map<Long, WebSocketSession> SESSIONS = new HashMap<>();

    /**
     * 获取WebSocket连接之后的操作
     *
     * @param session
     * @throws Exception
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {


        Long uid = (Long) session.getAttributes().get("uid");
        // 将当前用户的session放置到map中，后面会使用相应的session通信
        SESSIONS.put(uid, session);

        System.out.println("----------------->>>> 用户："+uid+",已上线");
    }


    /**
     * 发送与接收消息
     *
     * @param session
     * @param textMessage
     * @throws Exception
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage textMessage) throws Exception {

        Long uid = (Long) session.getAttributes().get("uid");

        JsonNode jsonNode = MAPPER.readTree(textMessage.getPayload());
        System.out.println("--------------->>>>> JsonNode对象打印： " + jsonNode.toPrettyString());
        Long toId = jsonNode.get("toId").asLong();
        String msg = jsonNode.get("msg").asText();

        //构造消息对象
        Message message = Message.builder().from(UserData.USER_MAP.get(uid)).to(UserData.USER_MAP.get(toId)).msg(msg).build();

        // 将消息保存到MongoDB
        message = messageDao.saveMessage(message);

        // 判断to用户是否在线
        WebSocketSession toSession = SESSIONS.get(toId);
        if (toSession != null && toSession.isOpen()) {
            //TODO 具体格式需要和前端对接
            toSession.sendMessage(new TextMessage(MAPPER.writeValueAsString(message))); // 更新消息状态为已读 this.messageDAO.updateMessageState(message.getId(), 2); }
        }
    }


    /**
     * 连接断开之后操作
     * @param session
     * @param status
     * @throws Exception
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        Long uid = (Long) session.getAttributes().get("uid");
        System.out.println("---------------->>>>用户："+uid+"断开连接");
        SESSIONS.remove(uid);
    }
}
